package cn.ultrarisk.scadmin.manager.biz.monitor.service;

import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.scadmin.manager.biz.monitor.dao.SolrReplicaMonitorDAO;
import cn.ultrarisk.scadmin.manager.biz.monitor.entity.SolrReplicaMonitor;
import cn.ultrarisk.scadmin.manager.biz.solr.context.SolrState;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrReplica;
import cn.ultrarisk.scadmin.manager.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class SolrReplicaMonitorService {
    @Autowired
    private SolrReplicaMonitorDAO solrReplicaMonitorDAO;

    public SolrReplicaMonitor createBySolrInfo(SolrReplica replica, SolrState state, JsonUtil.MapWrapper stateMap, Long createTime) {
        SolrReplicaMonitor monitor = new SolrReplicaMonitor(replica, state);
        monitor.setNumDocs(stateMap.getLongByPath("index.numDocs"));
        monitor.setMaxDocs(stateMap.getLongByPath("index.maxDoc"));
        monitor.setDeletedDocs(stateMap.getLongByPath("index.deletedDocs"));
        monitor.setSegmentCount(stateMap.getIntByPath("index.segmentCount"));
        monitor.setIndexHeapUsage(stateMap.getLongByPath("index.indexHeapUsageBytes"));
        monitor.setIndexSize(stateMap.getLongByPath("index.sizeInBytes"));
        monitor.setCreateTime(createTime);
        solrReplicaMonitorDAO.create(monitor);
        return monitor;
    }

    /**
     * 清除过期的SolrCache监控数据
     *
     * @query expiredTime
     */
    public void clearExpiredData(long expiredTime) {
        Query query = Query.ltQuery(SolrReplicaMonitor.CREATE_TIME, expiredTime);
        solrReplicaMonitorDAO.delete(query);
    }
}